/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.muni.fi.pa165.machineryrental.weblayer.validator;

import cz.muni.fi.pa165.machineryrental.dto.CustomerDTO;
import cz.muni.fi.pa165.machineryrental.dto.CustomerType;
import cz.muni.fi.pa165.machineryrental.dto.MachineDTO;
import cz.muni.fi.pa165.machineryrental.service.CustomerService;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

/**
 *
 * @author jostri
 */
@Component
public class CustomerValidator implements Validator {

    private final static String EmailPattern = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
    private final static String PhonePattern = "^\\u002b\\d\\d\\d \\d\\d\\d \\d\\d\\d \\d\\d\\d$";
    @Autowired
    private CustomerService customerService;

    @Override
    public boolean supports(Class<?> type) {
        return CustomerDTO.class.equals(type);
    }

    @Override
    public void validate(Object o, Errors errors) {
        System.out.println("Is validating");

        ValidationUtils.rejectIfEmpty(errors, "firstName", "customer.firstname.empty");
        ValidationUtils.rejectIfEmpty(errors, "lastName", "customer.lastname.empty");
        ValidationUtils.rejectIfEmpty(errors, "email", "customer.email.empty");
        ValidationUtils.rejectIfEmpty(errors, "phone", "customer.phone.empty");

        ValidationUtils.rejectIfEmpty(errors, "street", "customer.street.empty");
        ValidationUtils.rejectIfEmpty(errors, "city", "customer.city.empty");
        ValidationUtils.rejectIfEmpty(errors, "zipCode", "customer.zipcode.empty");
        ValidationUtils.rejectIfEmpty(errors, "country", "customer.country.empty");

        CustomerDTO customer = (CustomerDTO) o;

        if (customer.getCustomerType() == CustomerType.BUSINESS) {
            ValidationUtils.rejectIfEmpty(errors, "vatNumber", "customer.vatnumber.empty");
            ValidationUtils.rejectIfEmpty(errors, "companyNumber", "customer.companynumber.empty");
        }
        else {
            if (customer.getVatNumber() != null && !customer.getVatNumber().isEmpty()) {
                errors.rejectValue("vatNumber", "customer.busines.notrequired");
            }
            
            if (customer.getCompanyNumber() != null && !customer.getCompanyNumber().isEmpty()) {
                errors.rejectValue("companyNumber", "customer.busines.notrequired");
            }
        }

        if (customer.getEmail() != null && !customer.getEmail().isEmpty()) {
            if (!this.validatePattern(CustomerValidator.EmailPattern, customer.getEmail())) {
                errors.rejectValue("email", "customer.email.pattern");
            }
        }
        if (customer.getPhone() != null && !customer.getPhone().isEmpty()) {
            if (!this.validatePattern(CustomerValidator.PhonePattern, customer.getPhone())) {
                errors.rejectValue("phone", "customer.phone.pattern");
            }
        }

        // Customer id is bigger than 0? => Is edit formular, so we
        // dont check email - is read only
        if (customer.getId() == 0 && customer.getEmail() != null) {
            
            if (!this.customerService.isEmailUnique(customer.getEmail())) {
                errors.rejectValue("email", "customer.email.unique");
            }
            
            if (!this.customerService.isVATNumberUnique(customer.getVatNumber())) {
                errors.rejectValue("vatNumber", "customer.vat.unique");
            }
            
            if (!this.customerService.isCompanyNumberUnique(customer.getCompanyNumber())) {
                errors.rejectValue("companyNumber", "customer.companynumber.unique");
            }
        }
    }

    private boolean validatePattern(String regex, String value) {
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(value);
        return matcher.matches();
    }
}
